package com.cxd.performance.service.impl;


import com.cxd.performance.domain.MessageDomain;
import com.cxd.performance.domain.ScoringInfo;
import com.cxd.performance.exception.BusinessException;
import com.cxd.performance.service.MailSenderService;
import com.cxd.performance.service.SendScoringMailService;
import com.cxd.performance.utils.ExcelImportUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SendScoringMailServiceImpl implements SendScoringMailService {

    private static final String FILEPATH = "D:\\美创一组项目绩效\\";

    @Autowired
    private MailSenderService mailSenderService;

    @Override
    public void sendScoringMail(String filePath) {
        Map<String, Object> dataMap = ExcelImportUtils.importExcel(filePath, ScoringInfo.class);
        if (dataMap.isEmpty()) {
            throw new BusinessException("20001", "导入文件数据为空");
        }
        List<ScoringInfo> dataList = (List<ScoringInfo>) dataMap.get("dataList");
        log.info("excel解析数据为：{}",dataList);
        int count = 0;
        for (ScoringInfo score : dataList) {
            Workbook wb = getTemplate("excel", "scoring_template.xlsx");
            Sheet sheet = wb.getSheet("评分汇总");
            Row row = sheet.getRow(4);
            Cell cell1 = row.getCell(1);
            cell1.setCellValue(score.getSerialNumber());
            Cell cell2 = row.getCell(2);
            cell2.setCellValue(score.getProjectTeam());
            Cell cell3 = row.getCell(3);
            cell3.setCellValue(score.getEmployeeName());
            Cell cell4 = row.getCell(4);
            cell4.setCellValue(score.getDeliveryQualityScore());
            Cell cell5 = row.getCell(5);
            cell5.setCellValue(score.getWorkingAttitudeScore());
            Cell cell6 = row.getCell(6);
            cell6.setCellValue(score.getAttendanceScore());
            Cell cell7 = row.getCell(7);
            cell7.setCellValue(score.getWorkOvertimeScore());
            Cell cell8 = row.getCell(8);
            cell8.setCellValue(score.getRedBlackScore());
            Cell cell9 = row.getCell(9);
            cell9.setCellValue(score.getRecruitScore());
            Cell cell10 = row.getCell(10);
            cell10.setCellValue(score.getTutorScore());
            Cell cell11 = row.getCell(11);
            cell11.setCellValue(score.getShareScore());
            Cell cell12 = row.getCell(12);
            cell12.setCellValue(score.getDemandCreationScore());
            Integer totalScore = score.getDeliveryQualityScore() + score.getWorkingAttitudeScore() +
                    score.getAttendanceScore() + score.getWorkOvertimeScore() + score.getRedBlackScore()
                    + score.getRecruitScore() + score.getTutorScore() + score.getShareScore()
                    + score.getDemandCreationScore();
            Cell cell13 = row.getCell(13);
            cell13.setCellValue(totalScore);
            Cell cell14 = row.getCell(14);
            cell14.setCellValue(score.getRemark());

            Calendar cal = Calendar.getInstance();
            int currentMonth = cal.get(Calendar.MONTH);
            isChartPathExist(FILEPATH);
            String targetFilePath = FILEPATH+count+"_"+score.getEmployeeName()+"_"+currentMonth+"月份绩效评分.xlsx";
            try (FileOutputStream output=new FileOutputStream(targetFilePath);) {
                wb.write(output);//写入磁盘

                //发送邮件：
                String mail = score.getMail();
                if (!checkMail(mail)) {
                    log.error("第"+count+"行邮件格式错误,邮箱为：{}",mail);
                    throw new BusinessException("20001","邮件格式错误");
                }

                MessageDomain messageDomain = new MessageDomain();
                messageDomain.setTo(new String[]{mail});
                messageDomain.setSubject("美创1组_"+score.getEmployeeName()+"_"+currentMonth+"月份项目绩效评分明细");
                String content = "<html lang=\"en\">\n" +
                        "<head>\n" +
                        "    <meta charset=\"UTF-8\">\n" +
                        "    <meta ame=\"viewport\" cotet=\"width=device-width, iitial-scale=1.0\">\n" +
                        "    <title>Documet</title>\n" +
                        "</head>\n" +
                        "<body>\n" +
                        "    <div style='font-size:16px;'>&emsp;&emsp;如果您对本月项目绩效打分有任何疑义,请员工在收到邮件通知起3个工作日内发送邮件向各组长进行申诉。</div>\n" +
                        "    <div style='font-size:16px;'>若在申诉期间内未提出疑义，视为您认可本次绩效打分公布结果，各组长后续不再接受申诉，绩效打分结果以本次通知为准。</div><br>\n" +
                        "    <div style='font-size:24px;color: red;'>评分明细请看附件：</div><br><br>\n" +
                        "    <div style='font-size:16px;'>申诉对接人：</div>\n" +
                        "\t<div style='font-size:16px;'>美创1组项目经理:陈小东(邮箱：chexiaodog@e-lead.cn)</div>\n" +
                        "    <div style='font-size:16px;'>美创物流1组组长:陈小东(邮箱：chexiaodog@e-lead.cn)</div>\n" +
                        "    <div style='font-size:16px;'>美创物流2组组长:严楷(邮箱：yakai@e-lead.cn)</div>\n" +
                        "    <div style='font-size:16px;'>美创物流3组组长:张桂华(邮箱：zhagguihua@e-lead.cn)</div>\n" +
                        "    <div style='font-size:16px;'>美创物流4组组长:梁鸿毅(邮箱：liaghogyi@e-lead.cn)</div>\n" +
                        "</body>\n" +
                        "</html>";
                messageDomain.setContent(content);
                messageDomain.setFilePath(targetFilePath);
                mailSenderService.sendAttachmentsMail(messageDomain);
            }catch (Exception e) {
                log.error("导出项目绩效失败");
            }
            count++;

        }

    }

    private void isChartPathExist(String filepath) {
        File file = new File(filepath);
        if (!file.exists()) {
            log.info("dir not exists, create it ...");
            file.mkdir();
        }
    }

    private boolean checkMail(String mail) {
        if(mail.contains("@")&&mail.contains(".")) {
            if(mail.lastIndexOf(".")>mail.lastIndexOf("@")) {
                return true;
            }
        }else {
            return false;
        }
        return true;
    }

    private Workbook getTemplate(String folder, String fileName) {
        ClassLoader loader = SendScoringMailServiceImpl.class.getClassLoader();
        String path = (new StringBuilder()).append(folder).append(File.separator)
                .append(fileName).toString();
        InputStream in = loader.getResourceAsStream(path);
        Workbook wb = null;
        boolean isE2007 = true;
        if (fileName.endsWith(".xls"))
            isE2007 = false;
        try {
            if (isE2007) {
                wb = new XSSFWorkbook(in);
            } else {
                wb = new HSSFWorkbook(in);
            }
        } catch (IOException e) {
            log.error("获取excel模板失败", e);
        }
        return wb;
    }
}
